package com.Policing.Receive;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.widget.*;
import com.Policing.Adapter.Addrepairs_Adapter;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.AddRepairs_bean;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.senter.iot.support.openapi.uhf.UhfD2;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Grant_rfid extends BaseActivity implements OnDismissListener {
    private ImageView fh;//返回
    private Button check;
    private String url="http://"+ Ip_Set.IP+"/api/receivesInspect";
    private String urls="http://"+ Ip_Set.IP+"/api/receivesPut";
    private String rfid_url="http://"+ Ip_Set.IP+"/api/receivesInspectRfid";
    private List<AddRepairs_bean> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private TextView title_text;//标题
    private ListView Supplies_list;
    private boolean stop_rfid =true;
    private EditText Input_number;
    private boolean isrfid=true;
    private String coding,status;//领用单号。状态
    private Handler handler = new Handler();
    private String id;//登录人id
    private List<String> rfid_data = new ArrayList<>();
    private boolean state;

    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(Grant_rfid.this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private Button bt_Rfid,bt_scan,bt_upload;//rfid,扫码，上传
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
    }

    @Override
    public int intiLayout() {
        return R.layout.grant_rfid;
//设置子类的布局
    }

    @Override
    public void initView() {//初始化控件
        check = (Button) findViewById(R.id.check);
        fh = (ImageView) findViewById(R.id.fh);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("发放");
        Supplies_list = (ListView) findViewById(R.id.Supplies_list);
        bt_Rfid = (Button) findViewById(R.id.Rfid);
        bt_scan = (Button) findViewById(R.id.scan);
        bt_upload = (Button) findViewById(R.id.upload);
        Input_number = (EditText) findViewById(R.id.Input_number);
    }

    @Override
    public void initData() {//初始化数据
        Intent intent = getIntent();
        coding = intent.getStringExtra("coding_name");
         status =intent.getStringExtra("status");
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        bt_upload.setOnClickListener(v -> {
            if (lv_data.size()>0){
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, Grant_rfid.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            uploads();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Grant_rfid.this).show();

            }else {
                toastShort("请扫描需要发放的资产");
            }

        });
        check.setOnClickListener(v -> {
            Intent intent1 = new Intent(Grant_rfid.this, Receive_issued.class);
            intent1.putExtra("coding_name",coding);
            intent1.putExtra("status",status);
            startActivity(intent1);
        });
        bt_Rfid.setOnClickListener(v -> {
            try {
                if (isrfid==true){
                    if (UhfD2.getInstance().init() == true){
                        UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                    }
                    isrfid = false;
                }

            }catch (Exception E){
                toastShort("没有RFID模块");
                return;
            }
            if (stop_rfid){
                stop_rfid=false;
                start_read();
                bt_Rfid.setText("停止读取");
            }else {
                stop_rfid=true;
                state =false;
                bt_Rfid.setText("开启RFID");
            }

        });
        Input_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                Input_number.selectAll();
                if (!Input_number.getText().toString().trim().equals("")&&Input_number.length()>9){
                        upload(Input_number.getText().toString().trim());
                }else {
                    toastShort("错误的格式");
                }
            }
        });
        fh.setOnClickListener(v -> finish());
        bt_scan.setOnClickListener(v -> startQrCode());

    }
    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Grant_rfid.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Grant_rfid.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Grant_rfid.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Grant_rfid.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Grant_rfid.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Grant_rfid.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Grant_rfid.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            final String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
                upload(scanResult);
        }
    }
    private void upload(final String scanResult) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("assetNumber",scanResult)
                     .add("receivesId",coding)
                     .add("source", Since_case.set().getSource()); //传递键值对参数

            Request request = new Request.Builder()//创建Request 对象。
                    .url(url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    Log.i("123123", "error");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    //回调方法的使用与get异步请求相同
                    handler.post(() -> {
                        try {
                            Log.i("123123", responseData);
                            JSONObject json = new JSONObject(responseData);
                            Bitmap bitmap =null;
                            if (json.getString("state").equals("0")){
                                toastShort("失败");
                            }
                            if (json.getString("state").equals("1")){
                                lv_data.add(scanResult);
                                JSONObject jsonObject = json.getJSONObject("asset");
                                String assetName = jsonObject.getString("assetName");
                                String deptId = jsonObject.getString("deptId");
                                String assetNumber = jsonObject.getString("assetNumber");
                                String userId = jsonObject.getString("userId");
                                String model = jsonObject.getString("model");
                                String type = jsonObject.getString("type");
                             //   String remark = jsonObject.getString("remark");
                                if (jsonObject.getString("image").equals("")){ // wh  getResources().openRawResource(R.mipmap.null_po);
                                    @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                    bitmap = BitmapFactory.decodeStream(is);
                                }else {
                                    byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                    bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                }
                                Collections.reverse(data);
                                data.add(new AddRepairs_bean(bitmap,assetName,deptId,assetNumber,userId,model,type,"","类别",""));
                                Collections.reverse(data);
                                Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Grant_rfid.this,R.layout.addrepairs_item,data);
                                Supplies_list.setAdapter(adapter_item);
                            }
                            if (json.getString("state").equals("2")){
                                toastShort("未申请此类型的资产");

                            }
                            if (json.getString("state").equals("3")){
                                toastShort("非闲置资产");
                            }
                            if (json.getString("state").equals("4")){
                                toastShort("资产不存在");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    });

                }
            });

        }).start();
    }
    private void uploads() {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("assetNumbers",lv_data.toString())
                    .add("receivesId",coding)
                    .add("source",Since_case.set().getSource()); //传递键值对参数

            Request request = new Request.Builder()//创建Request 对象。
                    .url(urls)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    Log.i("123123", "error");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    Log.i("123123", responseData);
                    //回调方法的使用与get异步请求相同
                    handler.post(() -> {
                        try {
                            JSONObject json = new JSONObject(responseData);
                            if (json.getString("state").equals("0")){
                                toastShort("上传失败");
                            }
                            if (json.getString("state").equals("1")){
                                toastShort("上传成功");
                                finish();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    });

                }
            });

        }).start();
    }

    @Override
    public void onDismiss(Object o) {

    }
    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    handler.postDelayed(() -> RFID(rfid),500);
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });
    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void RFID(final String rfid) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("rfid",rfid).add("receivesId",coding); //传递键值对参数
            Request request = new Request.Builder()//创建Request 对象。
                    .url(rfid_url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    //回调方法的使用与get异步请求相同
                    handler.post(() -> {
                        try {
                            JSONObject json = new JSONObject(responseData);
                            Bitmap bitmap =null;
                            if (json.getString("state").equals("0")){
                                toastShort("失败");
                            }
                            if (json.getString("state").equals("1")){

                                JSONObject jsonObject = json.getJSONObject("asset");
                                String assetName = jsonObject.getString("assetName");
                                String deptId = jsonObject.getString("deptId");
                                String assetNumber = jsonObject.getString("assetNumber");
                                String userId = jsonObject.getString("userId");
                                String model = jsonObject.getString("model");
                                String type = jsonObject.getString("type");
                                lv_data.add(assetNumber);
                                String remark = jsonObject.getString("remark");
                                if (jsonObject.getString("image").equals("")){
                                    /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                    bitmap = BitmapFactory.decodeStream(is);*/
                                }else {
                                    byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                    bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                }
                                Collections.reverse(data);
                                data.add(new AddRepairs_bean(bitmap,assetName,deptId,assetNumber,userId,model,type,remark,"类别",""));
                                Collections.reverse(data);
                                Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Grant_rfid.this,R.layout.addrepairs_item,data);
                                Supplies_list.setAdapter(adapter_item);
                            }
                            if (json.getString("state").equals("2")){
                                toastShort("未申请此类型的资产");
                            }
                            if (json.getString("state").equals("3")){
                                toastShort("非闲置资产");
                            }
                            if (json.getString("state").equals("4")){
                                toastShort("资产不存在");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    });

                }
            });

        }).start();
    }
}
